﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Niazi.CRM.Business;
using Mani.Common;
using Mani.Common.Security;
using Niazi.CRM.Business.Model;
using System.Threading;
using System.Configuration;

namespace Niazi.CRM.Web
{
    public partial class new_order : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SecurityManager secManager = new SecurityManager();
            secManager.authProvider = new WebAuthorizationProvider();

            if (!secManager.IsActionPermitted("Orders_insert"))
            {
                Response.Redirect("~/access_denied.aspx?action_name=Orders_insert");
            }

            if (!Page.IsPostBack)
                Session["Orders"] = null;
        }

        [WebMethod]
        public static string[] GetCities()
        {
            CRMModelContainer db = new CRMModelContainer();
            return db.Cities.OrderBy( c => c.Name ).Select(c => c.Name).ToArray();
        }

        [WebMethod]
        public static string[] GetAirlines()
        {
            CRMModelContainer db = new CRMModelContainer();
            return db.Airlines.OrderBy( a => a.Name ).Select(a => a.Name).ToArray();
        }

        [WebMethod]
        public static string[] GetQuantityUnits()
        {
            CRMModelContainer db = new CRMModelContainer();
            return db.QuantityUnits.Select(q => q.Description).ToArray();
        }

        [WebMethod]
        public static string[] GetNewspapers()
        {
            CRMModelContainer db = new CRMModelContainer();
            return db.Newspapers.OrderBy( n => n.Name ).Select(n => n.Name).ToArray();
        }

        [WebMethod]
        public static string GetUnitPrice(string sourceCity, string destinationCity, string airline, string newspaper) 
        {
            if (sourceCity == "---" || destinationCity == "---" || airline == "---")
                return "0";

            CRMModelContainer db = new CRMModelContainer();

            var transfer = db.Transfers.Where(t => t.CitySource.Name == sourceCity && t.CityDestination.Name == destinationCity
                                                                    && t.Airline.Name == airline && t.Newspaper.Name == newspaper).FirstOrDefault();

            if (transfer == null)
                transfer = db.Transfers.Where(t => t.CitySource.Name == sourceCity && t.CityDestination.Name == destinationCity
                                                                    && t.Airline.Name == airline).FirstOrDefault();

            if (transfer == null)
                return "0";

            return transfer.UnitPrice.ToString();
        }

        [WebMethod]
        public static void AddOrder(string sourceCity, string destinationCity, string airline, string newspaper, string unitPrice, string quantity, string quantityUnit, string tax, string weight, string OrderDate, bool MinPrice, string packagingPrice, string stampPrice)
        {
            if (String.IsNullOrEmpty(sourceCity) || String.IsNullOrEmpty(destinationCity) || String.IsNullOrEmpty(airline) || String.IsNullOrEmpty(newspaper) || String.IsNullOrEmpty(unitPrice) || String.IsNullOrEmpty(tax))
                return;

            if (sourceCity == "---" || destinationCity == "---" || airline == "---" || newspaper == "---" || unitPrice == "---" || tax == "---")
                return;

            List<OrdersSession> orders = null;

            if ( HttpContext.Current.Session["Orders"] == null )
                orders = new List<OrdersSession>();
            else
                orders = (List<OrdersSession>)HttpContext.Current.Session["Orders"];

            orders.Add(new OrdersSession { SourceCity = sourceCity, DestinationCity = destinationCity, Airline = airline, Newspaper = newspaper, UnitPrice = unitPrice, Quantity = quantity, QuantityUnit = quantityUnit, Tax = tax, Weight = weight, OrderDate = OrderDate, SetMinPrice = MinPrice, PackagingPrice = packagingPrice, StampPrice = stampPrice });
            HttpContext.Current.Session["Orders"] = orders;
        }

        [WebMethod]
        public static long[] SaveOrders()
        {
            List<OrdersSession> orders = null;
            List<Order> SavedOrders = new List<Order>();

            if (HttpContext.Current.Session["Orders"] == null)
                throw new Exception("هیچ سفارشی برای ذخیره سازی وجود ندارد");
            else
                orders = (List<OrdersSession>)HttpContext.Current.Session["Orders"];

            try
            {
                CRMModelContainer db = new CRMModelContainer();

                foreach (OrdersSession item in orders)
                {
                    if (String.IsNullOrEmpty(item.SourceCity) || String.IsNullOrEmpty(item.DestinationCity) || String.IsNullOrEmpty(item.Airline) || String.IsNullOrEmpty(item.Newspaper) || String.IsNullOrEmpty(item.UnitPrice) || String.IsNullOrEmpty(item.Tax))
                        continue;

                    if (item.SourceCity == "---" || item.DestinationCity == "---" || item.Airline == "---" || item.Newspaper == "---" || item.UnitPrice == "---" || item.Tax == "---")
                        continue;

                    

                    Order o = new Order();
                    o.CitySource = db.Cities.Where(c => c.Name == item.SourceCity).FirstOrDefault();
                    o.CityDestination = db.Cities.Where(c => c.Name == item.DestinationCity).FirstOrDefault();
                    o.Airline = db.Airlines.Where(a => a.Name == item.Airline).FirstOrDefault();
                    o.Newspaper = db.Newspapers.Where(n => n.Name == item.Newspaper).FirstOrDefault();
                    o.OrderDate = item.OrderDate.ToDateTime();

                    if (db.Orders.Where(oi => oi.SourceCityId == o.SourceCityId && 
                                        oi.DestinationCityId == o.DestinationCityId && 
                                        oi.AirlineId == o.AirlineId && 
                                        oi.NewspaperId == o.NewspaperId &&
                                        oi.OrderDate.Value == o.OrderDate.Value).FirstOrDefault() != null)
                    {
                        HttpContext.Current.Session["Orders"] = null;
                        throw new Exception("بارنامه روزنامه " + o.Newspaper.Name + " تکراری می باشد و قبلا در همین تاریخ ثبت شده است ");
                    }
                    
                    
                    o.QuantityUnit = db.QuantityUnits.Where(q => q.Description == item.QuantityUnit).FirstOrDefault();
                    o.Quantity = Convert.ToDouble(item.Quantity);
                    o.UnitPrice = Convert.ToInt64(item.UnitPrice);
                    o.TaxPrice = Convert.ToInt64(item.Tax);
                    o.Discount = 0;
                    o.etcPrice = 0;
                    o.PackagingPrice = Convert.ToInt64(item.PackagingPrice);
                    o.StampPrice = Convert.ToInt64(item.StampPrice);
                    o.Weight = Convert.ToDouble(item.Weight);
                    o.TransportPrice = RoundNumber(Convert.ToInt64(o.UnitPrice * o.Weight));
                    
                    if (item.SetMinPrice)
                        o.TotalPrice = 70000L;
                    else
                        o.TotalPrice = RoundNumber(Convert.ToInt64((o.UnitPrice * o.Weight) + o.TaxPrice + o.PackagingPrice + o.StampPrice));

                    

                    db.AddToOrders(o);

                    Accounting accounting1 = new Accounting();
                    accounting1.AccountingDate = o.OrderDate;
                    accounting1.Credit = 0;
                    accounting1.Debit = o.TotalPrice;
                    accounting1.Description = "بدهی سند بارنامه ";
                    accounting1.Order = o;
                    accounting1.ContactId = o.Newspaper.ContactId;

                    Accounting accounting2 = new Accounting();
                    accounting2.AccountingDate = o.OrderDate;
                    accounting2.Credit = o.TotalPrice;
                    accounting2.Debit = 0;
                    accounting2.Description = "طلب سند بارنامه " + o.Newspaper.Name;
                    accounting2.Order = o;
                    accounting2.ContactId = Convert.ToInt64(ConfigurationManager.AppSettings["owner_contact"]); 
                    
                    db.AddToAccountings(accounting1);
                    db.AddToAccountings(accounting2);

                    SavedOrders.Add(o);
                }

                db.SaveChanges();
            }
            catch
            {
                throw;
            }
            finally
            {
                HttpContext.Current.Session["Orders"] = null;
            }

            return SavedOrders.Select(s => s.Id).ToArray();;
        }

        [WebMethod]
        public static void PrintOrder(long OrderId)
        {
            List<string> names = new List<string>();
            names.Add("OrderId");

            List<object> values = new List<object>();
            values.Add(OrderId);

            string connInfo = ConfigurationManager.ConnectionStrings["NiaziMembership"].ToString();
            CrystalReportManager manager = new CrystalReportManager("Barnameh", names, values);
            manager.Init(connInfo);
            manager.PrintToPrinter(ConfigurationManager.AppSettings["PrinterName"]);
            manager.Dispose();
        }

        private static long RoundNumber(long Number)
        {
            if (Number % 1000 != 0)
                Number = Number + (1000 - (Number % 1000));

            return Number;
                
        }
    }

    [Serializable]
    public class OrdersSession
    {
        public string SourceCity { get; set; }
        public string DestinationCity { get; set; }
        public string Airline { get; set; }
        public string Newspaper { get; set; }
        public string UnitPrice { get; set; }
        public string Quantity { get; set; }
        public string QuantityUnit { get; set; }
        public string PackagingPrice { get; set; }
        public string StampPrice { get; set; }
        public string Tax { get; set; }
        public string Weight { get; set; }
        public string OrderDate { get; set; }
        public bool SetMinPrice { get; set; }
    }
}